<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '原料需求单',
    enablePullDownRefresh: false,
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <page-meta :root-font-size="setting.rootFontSize"></page-meta>
  <view style="display: flex; flex-direction: column; height: 100vh; background-color: #f2f2f1">
    <view style="position: sticky; top: 0; z-index: 9999">
      <wd-navbar :title="`采购需求单`" :bordered="false" safeAreaInsetTop>
        <template #left>
          <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
        </template>
        <template #right>
          <uni-print-button
            v-if="!review"
            size="small"
            class="btn"
            type="text"
            kind="demand"
            :data="[{ ...form }]"
          >
            <view class="printer-icon">
              <wd-icon name="print" size="22px" color="white"></wd-icon>
              打印
            </view>
          </uni-print-button>
        </template>
      </wd-navbar>
    </view>
    <view class="p">
      <view style="flex: 1; overflow: auto">
        <wd-form ref="formRef" :model="form" :rules="rules">
          <th-card title="基础信息" :style="{ pointerEvents: isPreview ? 'none' : 'initial' }">
            <!-- <th-form> -->
            <th-form-item label="单据编号">
              <view class="text seq-no-text">
                {{ form.demandCode }}
                <!-- <wd-icon
                    name="refresh1"
                    color="#9d9595"
                    style="margin-right: 4rpx"
                    @click="getDemandCode('need_demandCode')"
                  ></wd-icon> -->
              </view>
            </th-form-item>
            <th-form-item label="日期">
              <view class="text seq-no-text">
                <wd-datetime-picker
                  prop="demandDate"
                  type="date"
                  v-model="form.demandDate"
                  label=""
                  :minDate="minDate"
                  :disabled="
                    form.taskId ||
                    !(
                      form.status == 0 ||
                      form.status == null ||
                      form.status == 3 ||
                      form.status == 9
                    )
                  "
                ></wd-datetime-picker>
              </view>
            </th-form-item>
            <th-form-item label="供应商">
              <!-- <wd-input type="text" v-model="form.cusName" placeholder="" no-border /> -->
              <view class="text seq-no-text" @click="showSelectPickerCompany">
                <template v-if="form.reviewStatus == 1">
                  {{ form.cusCode }}
                </template>
                <template v-else>
                  <wd-input
                    type="text"
                    prop="cusName"
                    readonly
                    v-model="form.cusName"
                    placeholder="请选择供应商"
                    no-border
                    style="width: 100%"
                    :disabled="
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    "
                  />
                </template>
              </view>
            </th-form-item>
            <th-form-item :label="'业务员'">
              <view class="text seq-no-text" @click="showSelectUser">
                <wd-input
                  type="text"
                  readonly
                  prop="personName"
                  v-model="form.personName"
                  :placeholder="`请选择业务员`"
                  no-border
                />
              </view>
            </th-form-item>
            <th-form-item label="业务部门">
              <text class="text seq-no-text">{{ form.deptName }}</text>
            </th-form-item>
            <th-form-item v-show="!review" label="所属公司">
              <text class="text seq-no-text">{{ form.tenantName }}</text>
            </th-form-item>
            <!-- </th-form> -->
          </th-card>
          <th-card title="产品需求信息">
            <!-- <template v-slot:titleRight>
              <view class="icon" @click.stop.prevent="showCommonMore = !showCommonMore">
                <wd-icon v-if="!showCommonMore" name="caret-down-small" size="22px"></wd-icon>
                <wd-icon v-else name="caret-up-small" size="22px"></wd-icon>
              </view>
            </template> -->
            <view :style="{ pointerEvents: isPreview ? 'none' : 'initial' }">
              <th-form-item label="需求类型">
                <!-- <wd-picker
                :columns="demandTypeList"
                label=""
                v-model="form.demandTypeCode"
                label-key="demandName"
                value-key="id"
                prop="demandType"
                placeholder="请选择需求类型"
                @confirm="changedemandType"
                :disabled="
                  form.taskId ||
                  !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                "
              ></wd-picker> -->

                <wd-col-picker
                  label=""
                  v-model="demandTypeCodeList"
                  :columns="demandTypeCascader"
                  value-key="value"
                  label-key="label"
                  style="width: 100%"
                  :column-change="columnChangedemandTypeCodeList"
                  @confirm="handleConfirmdemandTypeCodeList"
                  :display-format="displayFormat"
                  :readonly="
                    form.taskId ||
                    !(
                      form.status == 0 ||
                      form.status == null ||
                      form.status == 3 ||
                      form.status == 9
                    )
                  "
                ></wd-col-picker>
              </th-form-item>
              <th-form-item label="需求产品">
                <wd-input
                  type="text"
                  v-model="form.invName"
                  prop="invName"
                  placeholder="请输入需求产品"
                  no-border
                  :disabled="
                    form.taskId ||
                    !(
                      form.status == 0 ||
                      form.status == null ||
                      form.status == 3 ||
                      form.status == 9
                    )
                  "
                  use-suffix-slot
                  style="width: 100%"
                  @change="changeInv"
                  clearable
                >
                  <template
                    #suffix
                    v-if="
                      !(
                        form.taskId ||
                        !(
                          form.status == 0 ||
                          form.status == null ||
                          form.status == 3 ||
                          form.status == 9
                        )
                      )
                    "
                  >
                    <wd-icon
                      name="search"
                      size="16px"
                      color="#bfbfbf"
                      @click="searchInvList"
                    ></wd-icon>
                  </template>
                </wd-input>
              </th-form-item>
              <th-form-item label="需求产品规格">
                <wd-input
                  type="text"
                  v-model="form.invStd"
                  prop="invStd"
                  placeholder="请输入需求产品规格"
                  no-border
                  :disabled="
                    form.taskId ||
                    !(
                      form.status == 0 ||
                      form.status == null ||
                      form.status == 3 ||
                      form.status == 9
                    )
                  "
                />
              </th-form-item>

              <th-form-item label="是否有外来样">
                <!-- <wd-input type="text" v-model="form.sampleFlagName" placeholder="" no-border /> -->
                <wd-picker
                  :columns="samplaFlagList"
                  label=""
                  v-model="form.sampleFlag"
                  @confirm="changesampleFlagName"
                  prop="sampleFlag"
                  :disabled="
                    form.taskId ||
                    !(
                      form.status == 0 ||
                      form.status == null ||
                      form.status == 3 ||
                      form.status == 9
                    )
                  "
                />
              </th-form-item>
              <th-form-item
                label="外来样品编码"
                v-if="form.sampleFlag != '0' && form.sampleFlag != null && showCommonMore"
              >
                <view class="text seq-no-text">
                  <wd-input
                    v-model="form.sampleCode"
                    no-border
                    :disabled="
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    "
                    placeholder="外来样品编码"
                  ></wd-input>
                  <!-- {{ form.sampleCode }} -->
                  <wd-icon
                    name="refresh1"
                    color="#9d9595"
                    style="margin-right: 4rpx"
                    @click="getDemandCode('need_sampleCode')"
                  ></wd-icon>
                </view>
              </th-form-item>
              <th-form-item
                label="外来样品数量"
                v-if="form.sampleFlag != '0' && form.sampleFlag != null && showCommonMore"
              >
                <view class="seq-no-text">
                  <view style="flex: 1">
                    <wd-input
                      type="number"
                      v-model="form.samplesNum"
                      prop="samplesNum"
                      placeholder="请输入外来样品数量"
                      no-border
                      :disabled="
                        form.taskId ||
                        !(
                          form.status == 0 ||
                          form.status == null ||
                          form.status == 3 ||
                          form.status == 9
                        )
                      "
                    />
                  </view>
                  <view>
                    <wd-picker
                      :columns="sampleUnitList"
                      label=""
                      placeholder="请选择单位"
                      v-model="form.sampleUnit"
                      @confirm="getSampleUnit"
                      size="mini"
                      custom-class="sample-unit-class"
                      custom-value-class="sample-unit-custom-value-class"
                      :disabled="
                        form.taskId ||
                        !(
                          form.status == 0 ||
                          form.status == null ||
                          form.status == 3 ||
                          form.status == 9
                        )
                      "
                    />
                  </view>
                  <!-- <text v-if="form.sampleUnit" @click="getSampleUnit">{{ form.sampleUnit }}</text>
              <text v-else style="font-size: 28rpx; color: #9d9999" @click="getSampleUnit">请选择单位</text> -->
                </view>
              </th-form-item>
              <th-form-item
                label="外来样批次"
                v-if="form.sampleFlag != '0' && form.sampleFlag != null && showCommonMore"
              >
                <view class="text seq-no-text">
                  <wd-input
                    v-model="form.sampleBatch"
                    no-border
                    :disabled="
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    "
                    placeholder="外来样批次"
                  ></wd-input>
                  <wd-icon
                    name="refresh1"
                    color="#9d9595"
                    style="margin-right: 4rpx"
                    @click="getDemandCode('need_sampleBatch')"
                  ></wd-icon>
                </view>
              </th-form-item>
              <th-form-item label="要求完成时间" v-if="showCommonMore">
                <wd-datetime-picker
                  type="date"
                  v-model="form.askCompleteTime"
                  label=""
                  prop="askCompleteTime"
                  :minDate="minDate"
                  placeholder="请选择要求完成时间"
                  :disabled="
                    form.taskId ||
                    !(
                      form.status == 0 ||
                      form.status == null ||
                      form.status == 3 ||
                      form.status == 9
                    )
                  "
                ></wd-datetime-picker>
              </th-form-item>
              <th-form-item label="样品验证目的" class="form-demandDesc">
                <wd-select-picker
                  label=""
                  v-model="form.samplePurpose"
                  :columns="samplePurposeList"
                  value-key="label"
                  label-key="value"
                  size="small"
                  prop="samplePurpose"
                  placeholder="请选择样品验证目的"
                  :disabled="
                    form.taskId ||
                    !(
                      form.status == 0 ||
                      form.status == null ||
                      form.status == 3 ||
                      form.status == 9
                    )
                  "
                ></wd-select-picker>
              </th-form-item>
              <th-form-item
                label="其他信息"
                v-if="form.samplePurpose && form.samplePurpose.includes('其他')"
              >
                <view class="text seq-no-text">
                  <wd-input
                    v-model="form.samplePurposeDesc"
                    no-border
                    :readonly="
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    "
                    placeholder="其他信息"
                  ></wd-input>
                </view>
              </th-form-item>
              <th-form-item label="附件" class="form-demandDesc form-file">
                <view class="form-file-view">
                  <view
                    v-for="(file, index) in form.rdDemandFileEntity"
                    :key="file.fileUrl"
                    class="info-row-item"
                  >
                    <text @click="previewFileHandle(file.fileUrl)">{{ file.fileName }}</text>
                    <wd-icon
                      name="close-outline"
                      size="22px"
                      color="red"
                      @click.stop="removeFile(index)"
                      v-if="
                        !(
                          form.taskId ||
                          !(
                            form.status == 0 ||
                            form.status == null ||
                            form.status == 3 ||
                            form.status == 9
                          )
                        )
                      "
                    ></wd-icon>
                  </view>
                  <uploadFile
                    v-if="
                      !(
                        form.taskId ||
                        !(
                          form.status == 0 ||
                          form.status == null ||
                          form.status == 3 ||
                          form.status == 9
                        )
                      )
                    "
                    @complete="uploadComplete"
                  ></uploadFile>
                </view>
              </th-form-item>
              <th-form-item label="需求描述" class="form-demandDesc">
                <view style="width: 100%">
                  <wd-textarea
                    v-model="form.demandDesc"
                    placeholder="请填写需求描述"
                    auto-height
                    :maxlength="2000"
                    show-word-limit
                    no-border
                    prop="demandDesc"
                    :disabled="
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    "
                  />
                </view>
              </th-form-item>
            </view>

            <view class="exportModel" v-if="review" @click="showCommonMore = !showCommonMore">
              <text>{{ showCommonMore ? '收起' : '展开' }}</text>
            </view>
          </th-card>

          <th-card title="评审意见" v-if="review">
            <view class="pinsghen" style="width: 100%">
              <view
                style="overflow: auto"
                class="table-container"
                v-if="review && opinionList && opinionList.length"
              >
                <table class="analysis-table">
                  <tbody>
                    <tr>
                      <th style="width: 100rpx; min-width: 100rpx">姓名</th>
                      <th style="width: 280rpx; min-width: 280rpx">评审意见</th>
                    </tr>
                    <tr align="center" v-for="(item, index) in opinionList" :key="index">
                      <td>
                        <view>
                          {{ item.createName }}
                        </view>
                      </td>
                      <td>
                        <view>
                          {{ item.reviewOpinion }}
                        </view>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </view>
              <view>
                <wd-textarea
                  v-model="opinionParasm.reviewOpinion"
                  placeholder="请填写评审意见"
                  auto-height
                  :maxlength="2000"
                  no-border
                  style="min-height: 200rpx"
                  prop="reviewOpinion"
                  :disabled="!(form.reviewStatus != 2 && form.taskAllStatus == 1)"
                />
              </view>
            </view>
            <wd-button
              :round="false"
              style="width: 100%; margin-top: 20rpx"
              @click="saveDemandOpinion"
              v-if="form.reviewStatus != 2 && form.taskAllStatus == 1"
            >
              保存
            </wd-button>
          </th-card>

          <th-card
            v-if="
              (review || (form.rdFlag != null && form.reviewStatus == 1)) && form.reviewConclusion
            "
            title="需求评审"
          >
            <!-- <th-form-item v-if="!review" label="回复" class="form-demandDesc">
              <text class="text">{{ form.reply }}</text>
            </th-form-item> -->
            <th-form-item v-if="form.wayName" label="下一步任务" class="form-demandDesc">
              <text class="text">{{ form.wayName }}</text>
            </th-form-item>

            <!-- <template v-if="review || (form.rdFlag != null && form.reviewStatus == 1)"> -->
            <th-form-item label="回复" class="form-demandDesc" v-if="form.reply">
              <text class="text">{{ form.reply }}</text>
            </th-form-item>
            <th-form-item label="评审结论" class="form-demandDesc" v-if="form.reviewConclusion">
              <text class="text">{{ form.reviewConclusion }}</text>
            </th-form-item>
            <th-form-item label="是否可用" class="form-demandDesc" v-if="form.useFlag !== null">
              <text class="text">{{ form.useFlag == 0 ? '不可用' : '可用' }}</text>
            </th-form-item>
            <th-form-item label="评审结论描述" class="form-demandDesc" v-if="form.demandResult">
              <text class="text">{{ form.demandResult }}</text>
            </th-form-item>
            <th-form-item
              label="需求反馈方式"
              class="form-demandDesc"
              v-if="form.replyNeed !== null && form.replyNeed != 3"
            >
              <text class="text">
                {{
                  form.replyNeed == 1
                    ? '直接反馈'
                    : form.replyNeed == 2
                      ? '总经理确认后反馈'
                      : '不反馈'
                }}
              </text>
            </th-form-item>
            <th-form-item
              label="预计完成日期"
              class="form-demandDesc"
              v-if="form.estimatedCompletionTime"
            >
              <text class="text">
                {{
                  form.estimatedCompletionTime ? formatByDayjs(form.estimatedCompletionTime) : ''
                }}
              </text>
            </th-form-item>
            <th-form-item
              label="需求回复附件"
              class="form-demandDesc"
              v-if="form.rdReviewFileEntity && form.rdReviewFileEntity.length"
            >
              <view class="info-list">
                <view
                  class="info-list-main"
                  style="padding-top: 0; padding-left: 0; margin-top: 0; border: none"
                >
                  <view class="info-list-row">
                    <!-- <view class="info-list-label">附件</view> -->
                    <view class="info-list-value">
                      <view style="display: flex; flex-direction: column">
                        <view
                          v-for="file in form.rdReviewFileEntity"
                          :key="file.id"
                          @click="previewFileHandle(file.fileUrl)"
                          class="info-row-item"
                        >
                          {{ file.fileName }}
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </th-form-item>
            <!-- </template> -->
          </th-card>
          <th-card
            title="评审人员签字"
            v-if="(form.rdFlag != null && form.reviewStatus == 1) || review"
          >
            <reviews ref="reviewRef" @refreshDetail="init(form.id)"></reviews>
          </th-card>

          <th-card
            title="需求回复"
            v-if="
              !review &&
              form.replyFlag !== null &&
              (form.reply ||
                (form.rdReplyFileEntity && form.rdReplyFileEntity.length) ||
                (form.replyFlag == 1 &&
                  form.rdReplyChecksEntityTask &&
                  form.rdReplyChecksEntityTask.length) ||
                (form.replyFlag == 1 &&
                  form.rdReplyChecksEntityReport &&
                  form.rdReplyChecksEntityReport.length))
            "
          >
            <view>
              <th-form-item label="回复" class="form-demandDesc" v-if="form.reply">
                <text class="text">{{ form.reply }}</text>
              </th-form-item>
              <th-form-item label="是否可用" class="form-demandDesc" v-if="form.useFlag !== null">
                <text class="text">{{ form.useFlag == 0 ? '不可用' : '可用' }}</text>
              </th-form-item>
              <th-card
                title="任务检验报告"
                v-if="
                  form.replyFlag == 1 &&
                  form.rdReplyChecksEntityTask &&
                  form.rdReplyChecksEntityTask.length
                "
              >
                <view style="overflow: auto" class="table-container">
                  <table class="analysis-table">
                    <tbody>
                      <tr>
                        <th style="width: 320rpx; min-width: 9.5rem">检测项目(分析手段)</th>
                        <th style="width: 280rpx; min-width: 280rpx">检测指标</th>
                        <th style="width: 280rpx; min-width: 280rpx">指标单位</th>
                        <th style="width: 280rpx; min-width: 280rpx">检测结果</th>
                        <th style="width: 480rpx; min-width: 280rpx">报告</th>
                      </tr>
                      <tr
                        align="center"
                        v-for="(item, index) in form.rdReplyChecksEntityTask"
                        :key="index"
                      >
                        <td>
                          <view>
                            {{ item.analysisName }}
                          </view>
                        </td>
                        <td>
                          <view>
                            {{ item.itemName }}
                          </view>
                        </td>
                        <td>
                          <view>
                            {{ item.unit }}
                          </view>
                        </td>
                        <td>
                          <view>
                            {{ item.itemValue }}
                          </view>
                        </td>
                        <td>
                          <view>
                            <template
                              v-if="
                                item.qcExoticAttachmentsEntity &&
                                item.qcExoticAttachmentsEntity.length
                              "
                            >
                              <view
                                v-for="file in item.qcExoticAttachmentsEntity"
                                @click="previewFileHandle(file.url)"
                                :key="file.id"
                                class="info-row-item"
                                style="text-align: left"
                              >
                                {{ file.name }}
                              </view>
                            </template>
                          </view>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </view>
              </th-card>

              <th-card
                :title="`${form.projectName || ''}终检报告`"
                v-if="
                  form.replyFlag == 1 &&
                  form.rdReplyChecksEntityReport &&
                  form.rdReplyChecksEntityReport.length
                "
              >
                <view style="overflow: auto" class="table-container">
                  <table class="analysis-table">
                    <tbody>
                      <tr>
                        <th style="width: 320rpx; min-width: 9.5rem">检测项目(分析手段)</th>
                        <th style="width: 280rpx; min-width: 280rpx">检测指标</th>
                        <th style="width: 280rpx; min-width: 280rpx">指标单位</th>
                        <th style="width: 280rpx; min-width: 280rpx">检测结果</th>
                        <th style="width: 480rpx; min-width: 280rpx">报告</th>
                      </tr>
                      <tr
                        align="center"
                        v-for="(item, index) in form.rdReplyChecksEntityReport"
                        :key="index"
                      >
                        <td>
                          <view>
                            {{ item.analysisName }}
                          </view>
                        </td>
                        <td>
                          <view>
                            {{ item.itemName }}
                          </view>
                        </td>
                        <td>
                          <view>
                            {{ item.unit }}
                          </view>
                        </td>
                        <td>
                          <view>
                            {{ item.itemValue }}
                          </view>
                        </td>
                        <td>
                          <view>
                            <template
                              v-if="
                                item.qcMiddleAttachmentsEntity &&
                                item.qcMiddleAttachmentsEntity.length
                              "
                            >
                              <view
                                v-for="file in item.qcMiddleAttachmentsEntity"
                                @click="previewFileHandle(file.url)"
                                :key="file.id"
                                class="info-row-item"
                                style="text-align: left"
                              >
                                {{ file.name }}
                              </view>
                            </template>
                          </view>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </view>
              </th-card>
              <!-- <sampleAnalysiszeNew ref="sampleAnalysiszeRef"></sampleAnalysiszeNew> -->
              <th-card title="附件" v-if="form.rdReplyFileEntity && form.rdReplyFileEntity.length">
                <view class="form-file-view">
                  <view
                    v-for="(file, index) in form.rdReplyFileEntity"
                    :key="file.fileUrl"
                    class="info-row-item"
                  >
                    <text @click="previewFileHandle(file.fileUrl)">{{ file.fileName }}</text>
                    <wd-icon
                      name="close-outline"
                      size="22px"
                      color="red"
                      @click.stop="removeFile(index)"
                      v-if="
                        !(
                          form.taskId ||
                          !(
                            form.status == 0 ||
                            form.status == null ||
                            form.status == 3 ||
                            form.status == 9
                          )
                        )
                      "
                    ></wd-icon>
                  </view>
                </view>
              </th-card>
            </view>
          </th-card>
          <!-- 原来的数据兼容 -->
          <th-card
            title="需求回复"
            v-if="
              !review &&
              form.taskAllStatus == 2 &&
              form.replyFlag === null &&
              form.reply &&
              ((rdTaskDTOList && rdTaskDTOList.taskType != 2 && rdTaskDTOList.taskType != 9) ||
                !rdTaskDTOList)
            "
          >
            <view>
              <th-form-item label="回复" class="form-demandDesc" v-if="form.reply">
                <text class="text">{{ form.reply }}</text>
              </th-form-item>
            </view>
          </th-card>
          <!-- 原来的数据兼容 -->
          <th-card
            title="外来样检验任务评审"
            v-if="
              form.replyFlag === null &&
              rdTaskDTOList &&
              rdTaskDTOList.taskType == 2 &&
              form.taskAllStatus == '2'
            "
          >
            <view>
              <th-form-item label="回复" class="form-demandDesc">
                <text class="text">{{ form.reply }}</text>
              </th-form-item>
              <sampleAnalysiszeNew ref="sampleAnalysiszeRef"></sampleAnalysiszeNew>
              <th-card title="附件">
                <view class="form-file-view">
                  <view
                    v-for="(file, index) in rdTaskFileEntity"
                    :key="file.fileUrl"
                    class="info-row-item"
                  >
                    <text @click="previewFileHandle(file.fileUrl)">{{ file.fileName }}</text>
                    <wd-icon
                      name="close-outline"
                      size="22px"
                      color="red"
                      @click.stop="removeFile(index)"
                      v-if="
                        !(
                          form.taskId ||
                          !(
                            form.status == 0 ||
                            form.status == null ||
                            form.status == 3 ||
                            form.status == 9
                          )
                        )
                      "
                    ></wd-icon>
                  </view>
                </view>
              </th-card>
            </view>
          </th-card>
          <!-- 原来的数据兼容 -->
          <th-card
            title="其他任务单评审"
            v-if="
              form.replyFlag === null &&
              rdTaskDTOList &&
              rdTaskDTOList.taskType == 9 &&
              ((form.replyFlag == 1 && form.rdReplyFileEntity && form.rdReplyFileEntity.length) ||
                form.taskAllStatus == 2)
            "
          >
            <th-form-item label="回复" class="form-demandDesc" v-if="form.taskAllStatus == 2">
              <text class="text">{{ form.reply || '' }}</text>
            </th-form-item>
            <otherForm ref="otherFormRef"></otherForm>
          </th-card>

          <th-card title="需求指标" v-if="false">
            <wd-button
              :round="false"
              style="margin-bottom: 20rpx"
              @click="addCheckTargetList"
              type="text"
              v-if="
                !(
                  form.taskId ||
                  !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                )
              "
            >
              增行
            </wd-button>
            <view style="overflow: auto" class="table-container">
              <table class="analysis-table">
                <tbody>
                  <tr>
                    <th style="width: 320rpx; min-width: 9.5rem">检验指标名称</th>
                    <th style="width: 280rpx; min-width: 280rpx">U8指标</th>
                    <th style="width: 280rpx; min-width: 280rpx">客户指标</th>
                    <th
                      style="width: 280rpx; min-width: 280rpx"
                      v-if="
                        !(
                          form.taskId ||
                          !(
                            form.status == 0 ||
                            form.status == null ||
                            form.status == 3 ||
                            form.status == 9
                          )
                        )
                      "
                    >
                      操作
                    </th>
                  </tr>
                  <tr
                    align="center"
                    v-for="(item, index) in checkTargetList"
                    :key="index"
                    :class="[item.checktarget != item.cusCheckTarget ? 'line-red' : '']"
                  >
                    <td>
                      <view
                        v-if="
                          form.taskId ||
                          !(
                            form.status == 0 ||
                            form.status == null ||
                            form.status == 3 ||
                            form.status == 9
                          )
                        "
                      >
                        {{ item.cchkguidename }}
                      </view>
                      <view v-else>
                        <wd-input
                          v-model="item.cchkguidename"
                          clearable
                          no-border
                          style="background-color: transparent"
                          placeholder="请输入检验指标名称"
                          :disabled="item.addFlag == 0"
                        ></wd-input>
                      </view>
                    </td>
                    <td>
                      <wd-input
                        v-model="item.checktarget"
                        clearable
                        no-border
                        style="background-color: transparent"
                        placeholder=" "
                        disabled
                      ></wd-input>
                    </td>
                    <td>
                      <view
                        v-if="
                          form.taskId ||
                          !(
                            form.status == 0 ||
                            form.status == null ||
                            form.status == 3 ||
                            form.status == 9
                          )
                        "
                      >
                        {{ item.cusCheckTarget }}
                      </view>
                      <template v-else>
                        <wd-input
                          v-model="item.cusCheckTarget"
                          clearable
                          no-border
                          style="background-color: transparent"
                          placeholder="请输入客户指标"
                        ></wd-input>
                      </template>
                    </td>

                    <td
                      v-if="
                        !(
                          form.taskId ||
                          !(
                            form.status == 0 ||
                            form.status == null ||
                            form.status == 3 ||
                            form.status == 9
                          )
                        )
                      "
                    >
                      <view>
                        <wd-button
                          :disabled="item.addFlag == 0"
                          type="text"
                          :style="{
                            color: item.addFlag == 0 ? 'gray' : 'red',
                          }"
                          @click="delRow(index, item)"
                        >
                          删除
                        </wd-button>
                      </view>
                    </td>
                  </tr>
                </tbody>
              </table>
            </view>
          </th-card>
        </wd-form>

        <!-- <th-card
          title="需求回复确认"
          v-if="form.replyFlag == 1 && form.rdReplyFileEntity && form.rdReplyFileEntity.length"
        >
          <view class="form-file-view">
            <view
              v-for="(file, index) in form.rdReplyFileEntity"
              :key="file.fileUrl"
              class="info-row-item"
            >
              <text @click="previewFileHandle(file.fileUrl)">{{ file.fileName }}</text>
            </view>
          </view>
        </th-card> -->
        <th-card
          title="审核信息"
          v-if="(form.status == '1' || form.status == '2' || form.status == '3') && !review"
        >
          <view class="row-list">
            <view class="row" v-if="form.id && form.taskId">
              <!-- <view class="label">审核意见</view> -->
              <view class="value">
                <view class="mb2 mt2">
                  <h5>审核意见</h5>
                </view>
                <wd-textarea
                  type="textarea"
                  v-model="comment"
                  rows="6"
                  placeholder="请输入审核意见"
                  style="border: 1px solid #f7f7f7"
                ></wd-textarea>
              </view>
            </view>
            <view>
              <flowTable
                v-if="!review"
                ref="flowDetailsTableRef"
                :processInstanceId="form.instanceId"
              ></flowTable>
            </view>
          </view>
        </th-card>
      </view>

      <view class="flow-btn-fixed" v-if="form.id && form.taskId">
        <view class="btn_group" style="width: 100%">
          <view class="btn danger" @click="oncomplete(1)">
            <image src="@/static/reject.png" class="btn-icon"></image>
            拒绝
          </view>
          <view class="btn primary" @click="oncomplete(0)">
            <image src="@/static/tongyi.png" class="btn-icon"></image>
            同意
          </view>
        </view>
      </view>
      <view class="flow-btn-fixed" v-else>
        <view class="btn_group" style="width: 100%">
          <view
            class="btn primary"
            @click="onSave()"
            v-if="
              !(
                form.taskId ||
                !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
              ) && checkPremiss('need_rdDemand_add')
            "
          >
            <image src="@/static/save.png" class="btn-icon"></image>
            保存
          </view>
          <view
            class="btn primary"
            @click="onSubmit()"
            v-if="
              !(
                form.taskId ||
                !(
                  form.id &&
                  (form.status == null || form.status == 0 || form.status == 9 || form.status == 3)
                )
              ) && checkPremiss('need_rdDemand_submit')
            "
          >
            <image src="@/static/submit.png" class="btn-icon"></image>
            提交
          </view>
          <view
            class="btn primary"
            @click="onRevokeShow()"
            v-if="
              !(form.taskId || !(form.id && form.status == 1)) &&
              checkPremiss('need_rdDemand_revoke')
            "
          >
            <image src="@/static/rovoke.png" class="btn-icon"></image>
            撤回
          </view>
          <view
            class="btn primary"
            @click="onDel()"
            v-if="
              !(
                form.taskId ||
                !(
                  form.id &&
                  (form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                )
              ) && checkPremiss('need_rdDemand_del')
            "
          >
            <image src="@/static/del.png" class="btn-icon"></image>
            删除
          </view>
          <!-- (form.status == '2' || form.status == '3') &&
              isCanCancelApprover &&
              form.rdFlag != '1' &&
              form.rdFlag != '0' -->
          <view
            class="btn primary"
            @click="onCancelApprover()"
            v-if="
              

              ((form.status == '2' || form.status == '3') &&
                isCanCancelApprover &&
                (form.taskAllStatus == 1 || form.taskAllStatus == 0) &&
                ((form.reviewStatus != '2' && (form.autoTask == '0' || form.autoTask == null)) ||
                  form.autoTask == '1')) ||
              (form.instanceId === null &&
                (form.taskAllStatus == 1 || form.taskAllStatus == 0) &&
                (form.status == '2' || form.status == '3') &&
                ((form.reviewStatus != '2' && (form.autoTask == '0' || form.autoTask == null)) ||
                  form.autoTask == '1'))

            "
          >
            <image src="@/static/rovoke1.png" class="btn-icon"></image>
            弃审
          </view>
        </view>
      </view>
      <view style="width: 100; height: 10rpx; background-color: transparent"></view>
    </view>

    <leaguerPickerNew
      :show="selectUserShow"
      :filtration="true"
      :checked="selectList"
      :nop="1"
      :tenantId="form.tenantId"
      :returnDeptName="true"
      @hideModal="hideModal"
      @checkLeaguer="checkLeaguer"
    ></leaguerPickerNew>

    <pickerList
      :show="selectPickerCompany"
      :filtration="true"
      :checked="selectPickerCompanyList"
      :nop="1"
      :returnDeptName="true"
      @hideModal="hidePickerCompanyModal"
      @checkLeaguer="checkPickerCompanyLeaguer"
    ></pickerList>
  </view>

  <wd-popup v-model="revokeShow" position="bottom" @close="handleClose">
    <view style="display: flex; flex-direction: column; height: 100%">
      <wd-textarea
        v-model="revokeComment"
        placeholder="请填写撤回原因"
        no-border
        prop="revokeComment"
        class="reovke-textarea"
      />
      <view class="flow-btn-fixed">
        <view class="btn_group" style="width: 100%">
          <view class="btn danger" @click="handleClose">取消</view>
          <view class="btn primary" @click="onRevoke">撤回</view>
        </view>
      </view>
    </view>
  </wd-popup>
  <pickerInvList
    :show="selectpickerInvList"
    :filtration="true"
    :checked="selectpickerInvListList"
    :nop="1"
    :returnDeptName="true"
    @hideModal="hidepickerInvList"
    @checkLeaguer="checkpickerInvList"
  ></pickerInvList>
</template>

<script lang="ts" setup>
import { useSetting } from '@/stores/setting';
import {
  getGongyingObj,
  getPersonByPersonCode,
  getPmDict,
  getBaseDemandType,
  getSequenceNo,
  addObj,
  putObj,
  submitProcess,
  delObj,
  revokeProcess,
  selectTaskByProcessInstanceId,
  completeTask,
  listLastNodePerson,
  reviveProcess,
  selectCheckTarget,
  selectrdDocumentsPostUser,
  baseTrade,
  getDeptByCodeAndTenantId,
  getPersonByPersonCodeAndTantent,
  saveOpinion,
  updateOpinion,
  getOpinion,
} from '@/service/pm-requirement';
import { getObj as getTaskObj } from '@/service/pm-task';
import { formatByDayjs } from '@/utils/util';
import reviews from './component/review.vue';
import { useUserStore } from '@/stores/user';
import { useDict } from '@/hooks/dict';
import flowDetailsTable from '@/task/components/flowDetailsTable.vue';
import cache from '@/utils/cache';
import pickerInvList from '@/components/pickerInvList.vue';
import showModal from '@/utils/modal';
import pickerList from './component/pickerList.vue';
import sampleAnalysiszeNew from './component/sample-analysize.vue';
import otherForm from '@/pages/pm/task/component/other.vue';
import leaguerPickerNew from './component/leaguerPickerNew.vue';
import UniPrintButton from '@/pages/pm/assay-report/component/uniPrintButton.vue';
const setting = useSetting();
const minDate = ref(new Date().getTime());
const emits = defineEmits(['refresh']);
const tenantId = cache.getTenant();
const tenantName = cache.get('tenantName');
const userStore = useUserStore();
const flowDetailsTableRef: any = ref({});
let delrdDemandStandardlist = [];
const rdReviewFileEntity = ref([]);
// 提交表单数据
const form = reactive({
  id: null,
  demandDate: null,
  personName: null,
  demandType: null,
  demandTypeCode: null,
  deptHead: null,
  deptCode: null,
  applicationType: null,
  applicationCode: null,
  applicationList: [],
  samplesNum: null,
  demandDesc: null,
  sampleCoding: null,
  askCompleteTime: null,
  taskCode: null,
  userCode: null,
  invName: null,
  invDemand: null,
  sampleFlag: '0',
  demandCode: null,
  cusName: null,
  personCode: null,
  deptHeadCode: null,
  cusFlag: '3',
  demandResult: null,
  completeTime: null,
  // technologyHead: null,
  remark: null,
  // technologyHeadCode: null,
  taskId: null,
  instanceId: null,
  invStd: null,
  invCode: null,
  sampleCode: null,
  sampleBatch: null,
  deptName: null,
  rdFlag: null,
  chiefEngineer: null,
  deputyChiefEngineer: null,
  status: null,
  sampleFlagName: '否',
  deputyChiefEngineerUrl: null,
  chiefEngineerUrl: null,
  sampleUnit: null,
  sampleUnitCode: null,
  requestNumUnit: null,
  requestNumUnitCode: null,
  tenantName: null,
  tenantId: null,
  cusCode: null,
  deptId: null,
  taskFlag: null,
  // technologyHeadName: null,
  rdProjectUserEntity: [],
  rdDemandFileEntity: [],
  requestFlag: 0,
  requestNum: null,
  rdConnectEntity: [],
  reviewStatus: null,
  wayCode: null,
  reply: null,
  replyNeed: null,
  samplePurpose: [],
  samplePurposeDesc: '',
});
const showCommonMore = ref(false);
const selectrdDocumentsPostUserList = async () => {
  try {
    const res = await selectrdDocumentsPostUser({
      webSql: `documents_code = '1'`,
      size: 1000,
    });
    if (res.code !== 0) {
      return;
    }
    if (
      form.rdProjectUserEntity.length &&
      form.rdProjectUserEntity.find((item) => item.reviewFlag == 1 && item.signatureFlag == 1)
    ) {
      return;
    }
    const l = res.data.records.filter(
      (item) => item.reviewFlag == 1 && item.signatureFlag == 1 && item.chooseFlag == 0,
    );
    l.forEach((item) => {
      form.rdProjectUserEntity.push({
        personId: item.personId,
        userName: item.userName,
        userCode: item.userCode,
        userType: item.documentsPostCode,
        documentsName: item.documentsName,
        documentsCode: item.documentsCode,
        documentsId: item.documentsId,
        documentsPostCode: item.documentsPostCode,
        documentsPostName: item.documentsPostName,
        processCode: 1,
        reviewFlag: item.reviewFlag,
        signatureFlag: item.signatureFlag,
        chooseFlag: item.chooseFlag,
      });
    });
  } catch (err) {}
};
const samplePurposeList = ref([
  {
    label: '降低成本',
    value: '降低成本',
  },
  {
    label: '质量优化',
    value: '质量优化',
  },
  {
    label: '开发新产品',
    value: '开发新产品',
  },
  {
    label: '其他',
    value: '其他',
  },
]);
const getProjectName = (item, type = 0) => {
  console.log(form.rdProjectUserEntity, item);
  const l = form.rdProjectUserEntity.filter((f) => f.userCode == item.userCode);
  let s = '';
  if (l.length) {
    console.log('s', s);
    if (type == 0) {
      s = l.map((item) => item.userName).join(',');
      return s;
    } else {
      // s = l.map((item) => item.userUrl).join(',');
      s = l[0]['userUrl'];
      return s;
    }
  } else {
    return s;
  }
};
const reviewRef = ref(null);
const oldrdDemandStandard = ref([]);
const rdTaskDTOList = ref(null);
const sampleAnalysiszeRef = ref(null);
const tableRefs = ref({});
const otherFormRef = ref(null);
const taskRequirements = ref('');
const taskRdFlag = ref('');
const setItemRef = (e, item) => {
  tableRefs.value[item] = e;
};
const rdTaskFileEntity = ref([]);
const init = (id) => {
  uni.showLoading({
    mask: true,
  });
  getGongyingObj({ id })
    .then((res) => {
      console.log('res', res);
      if (res.code == 0) {
        let samplePurpose = [],
          samplePurposeReal = [];
        if (res.data?.samplePurpose) {
          if (Array.isArray(res.data.samplePurpose)) {
            samplePurpose = res.data.samplePurpose;
          } else {
            samplePurpose = res.data.samplePurpose.split(',');
          }
          // ['降低成本','质量优化','开发新产品'].map(item=>{

          // })
          samplePurpose
            .filter((item) => item)
            .map((item) => {
              if (item == '降低成本' || item == '质量优化' || item == '开发新产品') {
                samplePurposeReal.push(item);
              } else {
                samplePurposeReal.push('其他');
                res.data.samplePurposeDesc = item;
              }
              // if (['降低成本','质量优化','开发新产品'])
            });
          res.data.samplePurpose = samplePurposeReal;
        }

        Object.assign(form, res.data);
        // if (form.samplePurpose) {
        //   const
        //   const curr = form.samplePurpose
        // }
        form.applicationList = res.data.applicationCode?.split(',') || [];
        if (form.replyFlag === null && form.rdTaskDTOList && form.rdTaskDTOList.length) {
          const rArr = form.rdTaskDTOList.filter(
            (item) => (item.taskType == 2 || item.taskType == 9) && item.isUse == 1,
          );
          // 排序
          if (rArr.length > 1) {
            rArr.sort((a, b) => {
              const nameA = new Date(a.createTime).getTime();
              const nameB = new Date(b.createTime).getTime(); // 忽略大小写
              if (nameA < nameB) {
                return 1;
              }
              if (nameA > nameB) {
                return -1;
              }
              return 0;
            });
            rdTaskDTOList.value = rArr[0];
            // if (rdTaskDTOList.value.taskType == 2) {
            try {
              getTaskObj({ id: rdTaskDTOList.value.id })
                .then((res) => {
                  if (res.code != 0) {
                    uni.showToast({
                      mask: true,
                      title: `获取数据失败, 失败原因: ${res.msg}`,
                      icon: 'none',
                    });
                    return;
                  }
                  taskRequirements.value = rdTaskDTOList.value.requirements;
                  taskRdFlag.value = rdTaskDTOList.value.rdFlag;
                  nextTick(() => {
                    if (rdTaskDTOList.value.taskType == 2) {
                      sampleAnalysiszeRef?.value?.init(res.data);
                    } else if (rdTaskDTOList.value.taskType == 9) {
                      // res.data.rdTaskFileEntity = form.rdReplyFileEntity || [];
                      otherFormRef.value?.init(res.data);
                    }
                  });
                })
                .finally(() => {});
            } catch (error) {
              console.log('err', error);
            }
            // }
          } else {
            if (rArr.length > 0) {
              rdTaskDTOList.value = rArr[0];
              // if (rdTaskDTOList.value.taskType == 2) {
              try {
                getTaskObj({ id: rdTaskDTOList.value.id })
                  .then((res) => {
                    if (res.code != 0) {
                      uni.showToast({
                        mask: true,
                        title: `获取数据失败, 失败原因: ${res.msg}`,
                        icon: 'none',
                      });
                      return;
                    }
                    taskRequirements.value = rdTaskDTOList.value.requirements;
                    taskRdFlag.value = rdTaskDTOList.value.rdFlag;
                    nextTick(() => {
                      if (rdTaskDTOList.value.taskType == 2) {
                        sampleAnalysiszeRef.value?.init(res.data);
                      } else if (rdTaskDTOList.value.taskType == 9) {
                        // res.data.rdTaskFileEntity = form.rdReplyFileEntity || [];
                        otherFormRef.value?.init(res.data);
                      }
                    });
                  })
                  .finally(() => {});
              } catch (error) {
                console.log('err', error);
              }
              // }
            } else {
              rdTaskDTOList.value = null;
            }
          }
        }
        // } else {
        //   if (form.taskAllStatus == 2 && form.replyFlag == 1) {
        //     rdReviewFileEntity.value = form.rdReplyFileEntity || [];
        //   }
        // }

        // let demandTypeL = [];
        // if (res.data.cusFlag == '1') {
        //   demandTypeL = [
        //     {
        //       value: '4',
        //       label: '新产品',
        //     },
        //     {
        //       value: '5',
        //       label: '工艺改进思路',
        //     },
        //   ];
        // } else {
        //   demandTypeL = [
        //     {
        //       value: '1',
        //       label: '来样定制',
        //       children: [
        //         {
        //           value: '10',
        //           label: '检测分析',
        //         },
        //         {
        //           value: '11',
        //           label: '定制样品',
        //         },
        //       ],
        //     },
        //     {
        //       value: '2',
        //       label: '按指标定制',
        //       children: [
        //         {
        //           value: '20',
        //           label: '确认是否能做',
        //         },
        //         {
        //           value: '21',
        //           label: '提供样品',
        //         },
        //         {
        //           value: '22',
        //           label: '配方验证',
        //         },
        //       ],
        //     },
        //     {
        //       value: '3',
        //       label: '信息咨询',
        //       children: [
        //         {
        //           value: '30',
        //           label: '延长保质期',
        //         },
        //         {
        //           value: '31',
        //           label: '调查问卷',
        //         },
        //       ],
        //     },
        //   ];
        // }

        // demandTypeCascader.value = [demandTypeL];
        setdemandTypeCascader(res.data.cusFlag);

        setTimeout(() => {
          nextTick(() => {
            try {
              // const l = res.data.demandType.split(' / ');
              // const demandTypeCodeList1 = [];
              // const o = demandTypeCascader.value[0].find((d) => d.label == l[0]);
              // demandTypeCodeList1.push(o.value);
              // if (l.length == 2) {
              //   const o2 = o.children.find((d) => d.label == l[1]);
              //   demandTypeCascader.value.push(o.children);
              //   demandTypeCodeList1.push(o2.value);
              // }
              if (form.rdFlag != null) {
                reviewRef.value?.init(form);
                // reviewRef.value.init({
                //   id: form.id,
                //   taskCode: form.taskCode,
                //   demandCode: form.demandCode,
                // });
              }
              // demandTypeCodeList.value = demandTypeCodeList1;
              demandTypeCodeList.value = [form.demandTypeCode];
            } catch (error) {
              console.log('err', error);
            }
          });
        }, 0);

        form.askCompleteTime = new Date(form.askCompleteTime);
        form.demandDate = new Date(form.demandDate);
        if (res.data.instanceId) {
          selectTaskByProcessInstanceId({
            processInstanceId: res.data.instanceId,
          })
            .then((res) => {
              form.taskId = res.data && res.data.taskId ? res.data.taskId : null;
            })
            .catch(() => {
              form.taskId = null;
            });
          getCancelApprover();
          console.log('form', form);
        }

        if (res.data.rdDemandStandard && res.data.rdDemandStandard.length) {
          isShowCheckTarget.value = true;
          oldrdDemandStandard.value = res.data.rdDemandStandard;
          // 判断有多少行
          // const line = [];
          // res.data.rdDemandStandard.forEach((item) => {
          //   const o = line.find((l) => l == item.standardName);
          //   if (!o) {
          //     line.push(item.standardName);
          //   }
          // });
          // const allList = [];
          // line.forEach((item) => {
          //   const l = res.data.rdDemandStandard.filter((e) => e.standardName == item);
          //   let o = {};
          //   l.forEach((item) => {
          //     o = { ...item, ...o };
          //     if (item.addFlag == 0) {
          //       if (item.standardType == 1) {
          //         o['cchkguidename'] = item.standardName;
          //         o['cchkguidecode'] = item.standardCode;
          //         o['checktarget'] = item.standardValue;
          //       } else {
          //         o['cchkguidename'] = item.standardName;
          //         o['cchkguidecode'] = item.standardCode;
          //         o['cusCheckTarget'] = item.standardValue;
          //       }
          //     } else {
          //       o['cchkguidename'] = item.standardName;
          //       o['cchkguidecode'] = item.standardCode;
          //       o['cusCheckTarget'] = item.standardValue;
          //     }
          //     o['addFlag'] = item.addFlag;
          //     o['id'] = item.id;
          //   });
          //   allList.push(o);
          // });
          // checkTargetList.value = allList;
          checkTargetList.value = res.data.rdDemandStandard
            .filter((item) => item.delFlag != 1)
            .map((item) => {
              return {
                ...item,
                cchkguidename: item.standardName,
                cchkguidecode: item.standardCode,
                checktarget: item.standardValue,
                cusCheckTarget: item.standardValuePm,
              };
            });
        } else {
          isShowCheckTarget.value = false;
          oldrdDemandStandard.value = [];
        }
        if (res.data.instanceId) {
          nextTick(() => {
            flowDetailsTableRef.value &&
              flowDetailsTableRef.value.getFlowDetails &&
              flowDetailsTableRef.value.getFlowDetails();
          });
        }
        getSampleList(res.data.demandTypeCode, false);

        // 限制样品
        if (res.data.demandTypeCode == '21') {
          requestFlagList.value = defaultrequestFlagList.filter((item) => item.value != 0);
        } else {
          requestFlagList.value = defaultrequestFlagList;
        }
        // requestFlagList.value = defaultrequestFlagList;

        if (!(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)) {
          requestFlagList.value = defaultrequestFlagList;
        }
        if (review.value) {
          rdReviewOpinionHandle();
        }
      } else {
        uni.showToast({
          mask: true,
          icon: 'none',
          title: `获取数据失败，失败原因${res.msg}`,
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};
const isPreview = ref(false);
const review = ref(false);
onLoad(async (options) => {
  console.log('opp', options);
  let opt = options;
  if (options.params) {
    opt = JSON.parse(options.params);
  }
  let customerDemandType = '供应需求';
  isPreview.value == +opt.isPreview > 0 ? true : false;
  review.value = +opt.review > 0 ? true : false;
  if (!review.value) {
    showCommonMore.value = true;
  }
  form.tenantId = tenantId;
  form.tenantName = tenantName;
  // await getDict(customerDemandType);
  await getDict(opt.cusFlag);
  const { id } = opt;
  if (id) {
    init(id);
  } else {
    // getDemandCode('need_demandCode');
    form.demandDate = formatByDayjs(new Date(), 'YYYY-MM-DD 00:00:00');
  }
  // selectrdDocumentsPostUserList();
});

onUnload(() => {
  uni.$off('pm-inv');
});

const goBack = () => {
  uni.navigateBack();
  uni.$off('pm-inv');
};

const demandTypeList = ref([]);
const applicationTypeList = ref([]);
const sampleUnitList = ref([]);
const { pm_sample_flag_gongying } = useDict('pm_sample_flag_gongying');
const demandTypeCascader = ref([]);
const demandTypeCodeList = ref([]);
const getDict = async (type) => {
  // await getBaseDemandType({ demandSource: type, pageSize: -1, deleteFlag: 0 }).then((res) => {
  //   demandTypeList.value = res.data.records;
  // });

  // getPmDict({ dictType: 'applicationType', pageSize: -1 }).then((res) => {
  //   applicationTypeList.value = res.data.records;
  // });

  // await getapplicationTypeList();

  await getPmDict({ dictType: 'pm_need_unit', pageSize: -1 }).then((res) => {
    sampleUnitList.value = res.data.records;
  });

  // let demandTypeL = [];
  // if (type == '1') {
  //   demandTypeL = [
  //     {
  //       value: '4',
  //       label: '新产品',
  //     },
  //     {
  //       value: '5',
  //       label: '工艺改进思路',
  //     },
  //   ];
  // } else {
  //   demandTypeL = [
  //     {
  //       value: '1',
  //       label: '来样定制',
  //       children: [
  //         {
  //           value: '10',
  //           label: '检测分析',
  //         },
  //         {
  //           value: '11',
  //           label: '定制样品',
  //         },
  //       ],
  //     },
  //     {
  //       value: '2',
  //       label: '按指标定制',
  //       children: [
  //         {
  //           value: '20',
  //           label: '确认是否能做',
  //         },
  //         {
  //           value: '21',
  //           label: '提供样品',
  //         },
  //         {
  //           value: '22',
  //           label: '配方验证',
  //         },
  //       ],
  //     },
  //     {
  //       value: '3',
  //       label: '信息咨询',
  //       children: [
  //         {
  //           value: '30',
  //           label: '延长保质期',
  //         },
  //         {
  //           value: '31',
  //           label: '调查问卷',
  //         },
  //       ],
  //     },
  //   ];
  // }

  // demandTypeCascader.value = [demandTypeL];

  setdemandTypeCascader(type);
};

const getApplicationType = (e) => {
  form.applicationType = e.selectedItems.map((item) => item.value).join(',');
  form.applicationCode = e.selectedItems.map((item) => item.label).join(',');
};

const getDemandCode = (tableName) => {
  if (
    form.taskId ||
    !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
  ) {
    return;
  }
  if (
    form.taskId ||
    !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
  ) {
    return;
  }
  uni.showLoading({
    mask: true,
  });
  getSequenceNo({ tableName })
    .then((res) => {
      if (tableName == 'need_demandCode') {
        // form.demandCode = res.data;
        if (form.cusFlag == '0') {
          form.demandCode = `CD${res.data}`;
        } else {
          form.demandCode = `DE${res.data}`;
        }
      } else if (tableName == 'need_sampleCode') {
        form.sampleCode = `YP${res.data}`;
      } else if (tableName == 'need_sampleBatch') {
        form.sampleBatch = `PC${res.data}`;
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const selectUserShow = ref(false);
const selectList = ref([]);
const hideModal = () => {
  selectUserShow.value = false;
};
const checkLeaguer = (e) => {
  form.personCode = e[0].personCode;
  form.personName = e[0].personName;
  form.deptName = e[0].deptName;
  // form.deptCode = e.row.deptCode;
  form.deptCode = e[0].deptId;
  form.deptId = e[0].deptId;
};
const showSelectUser = () => {
  if (
    form.taskId ||
    !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
  ) {
    return;
  }
  selectUserShow.value = true;
};

// 选择客户
const selectPickerCompany = ref(false);
const selectPickerCompanyList = ref([]);
const tenantTreeId = ref('');
const hidePickerCompanyModal = () => {
  selectPickerCompany.value = false;
};

const getPersonByPersonCodeHandle = (cusPerson, tenantId) => {
  getPersonByPersonCode({
    personCode: cusPerson,
    tenantId: tenantId,
    currentFlag: 1,
  }).then((res) => {
    // form.personName = res.data.personName;
    // form.personCode = res.data.personCode;

    const { hrPersonDeptList } = res.data;
    const o = hrPersonDeptList.find(
      (item) => item.mainDeptFlag == '1' && item.tenantId == tenantId,
    );
    form.deptId = o.deptId;
    form.deptName = o.deptName;
    form.deptCode = o.deptId;
  });
};

const checkPickerCompanyLeaguer = (e) => {
  // const { cusPerson } = e[0];
  form.cusName = e[0].venName;
  form.cusCode = e[0].venCode;
  form.tenantId = e[0].tenantId;
  form.tenantName = e[0].tenantName;
  tenantTreeId.value = e[0].tenantId;
  form.personName = userStore.userInfos.user.name;
  form.personCode = userStore.userInfos.user.username;
  if (!form.personCode) return;

  getPersonByPersonCodeAndTantent({
    tenantId: form.tenantId,
    userId: userStore.userInfos.user.userId,
  })
    .then((res) => {
      if (res.code == 0) {
        if (!res.data?.deptId) {
          form.deptId = '';
          form.deptName = '';
          form.deptCode = '';
          form.personCode = '';
          form.personName = '';
          uni.showToast({
            title: `账套：${form.tenantName} 里没有该用户,请重新选择业务员`,
            icon: 'none',
          });
          return;
        }
        form.deptId = res.data.deptId;
        form.deptName = res.data.deptName;
        form.deptCode = res.data.deptId;
        form.personCode = res.data.personCode;
        // form.tenantName = e.row.tenantName;
      } else {
        form.deptId = '';
        form.deptName = '';
        form.deptCode = '';
        form.personCode = '';
        form.personName = '';
        uni.showToast({
          title: `账套：${form.tenantName} 里没有该用户,请重新选择业务员`,
          icon: 'none',
        });
      }
    })
    .catch((err) => {});
  // getPersonByPersonCode({
  //   personCode: cusPerson,
  //   tenantId: e[0].tenantId,
  //   currentFlag: 1,
  // }).then((res) => {
  //   form.personName = res.data.personName;
  //   form.personCode = res.data.personCode;

  //   const hrPersonDeptList = res.data.hrPersonDeptList;
  //   const o = hrPersonDeptList.find(
  //     (item) => item.mainDeptFlag == '1' && item.tenantId == e[0].tenantId,
  //   );
  //   form.deptId = o.deptId;
  //   form.deptName = o.deptName;
  //   form.deptCode = o.deptId;
  // });

  // if (cusDeptCode) {
  //   getDeptByCodeAndTenantId({
  //     deptCode: cusDeptCode,
  //     tenantId: e[0].tenantId,
  //   })
  //     .then((res) => {
  //       const data1 = res;
  //       form.deptId = data1.deptId;
  //       form.deptName = data1.name;
  //       form.deptCode = data1.deptId;
  //     })
  //     .catch((err) => {
  //       getPersonByPersonCodeHandle(cusPerson, e[0].tenantId);
  //     });
  // } else {
  //   getPersonByPersonCodeHandle(cusPerson, e[0].tenantId);
  // }
};
const showSelectPickerCompany = () => {
  if (
    form.taskId ||
    !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
  ) {
    return;
  }
  selectPickerCompany.value = true;
};

// 是否外来杨
const changesampleFlagName = (e, label = null, type = 0) => {
  form.sampleFlagName = type == 1 ? label : e.selectedItems.label;
  const v = type == 1 ? e : e.value;
  if (v != '0') {
    getDemandCode('need_sampleCode');
    getDemandCode('need_sampleBatch');
  }
  // 默认单位
  if (!form.sampleUnit) {
    form.sampleUnit = 'g';
    form.sampleUnitCode = 'g';
  }
};

//
const changeRequestFlag = () => {
  if (!form.requestNumUnit) {
    form.requestNumUnit = 'g';
    form.requestNumUnitCode = 'g';
  }
};

const rules: any = computed(() => {
  return {
    demandDate: [
      {
        required: true,
        message: '日期不能为空',
      },
    ],
    cusName: [
      {
        // required: true,
        required: form.cusFlag == '0',
        message: '客户不能为空',
      },
    ],
    personName: [
      {
        required: true,
        message: `业务员不能为空`,
      },
    ],
    demandType: [{ required: true, message: '需求类型不能为空' }],
    invName: [{ required: true, message: '需求产品不能为空' }],
    invStd: [{ required: true, message: '产品规格不能为空' }],
    // applicationType: [{ required: true, message: '应用领域不能为空' }],
    // invDemand: [{ required: true, message: '年需求量/吨不能为空' }],
    sampleFlag: [{ required: true, message: '是否有外来样不能为空' }],
    sampleCode: [{ required: form.sampleFlag != '0', message: '样品编码不能为空' }],
    samplesNum: [
      { required: form.sampleFlag != '0', message: '样品数量不能为空' },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (form.sampleUnitCode || form.sampleFlag == '0') {
            return Promise.resolve();
          }
          return Promise.reject('请选择单位');
        },
      },
    ],
    sampleBatch: [{ required: form.sampleFlag != '0', message: '来样批次不能为空' }],
    askCompleteTime: [{ required: true, message: '要求完成时间不能为空' }],
    demandDesc: [{ required: true, message: '需求描述不能为空' }],
    requestNum: [
      {
        validator: (rule: any, value: any, callback: any) => {
          if (form.requestFlag == 0 || form.requestFlag == null) {
            return Promise.resolve();
          }
          if (form.requestNum === '' || form.requestNum === null) {
            return Promise.reject('请输入提供样品数量');
          }
          return Promise.resolve();
        },
      },
    ],
  };
});

const onCancel = () => {
  uni.navigateBack({});
};
const formRef: any = ref({});
const onSave = (isSubmit = false) => {
  formRef.value.validate().then(({ valid, errors }) => {
    if (!valid) return false;

    uni.showLoading({
      mask: true,
    });

    let rdDemandStandard = [];
    // if (checkTargetList.value && checkTargetList.value.length) {
    rdDemandStandard = checkTargetList.value.map((item) => {
      return {
        ...item,
        standardCode: item.cchkguidecode,
        standardName: item.cchkguidename,
        standardValue: item.checktarget,
        standardValuePm: item.cusCheckTarget,
      };
    });
    let delList = [];
    delrdDemandStandardlist.forEach((item) => {
      const o = delCheckTargetList.value.find((d) => item.id == d.id);
      if (!o) {
        delList.push(item);
      }
    });
    delList = delList.concat(delCheckTargetList.value);
    rdDemandStandard = rdDemandStandard.concat(delList);
    // }

    // rdDemandStandard = rdDemandStandard.concat(delCheckTargetList.value);
    rdDemandStandard = rdDemandStandard.map((item) => {
      return {
        ...item,
        demandCode: form.demandCode,
        tenantId,
      };
    });

    // const delrdDemandStandardlist = [];
    // if (oldrdDemandStandard.value && oldrdDemandStandard.value.length) {
    //   oldrdDemandStandard.value.forEach((item) => {
    //     const o = rdDemandStandard.find(
    //       (r) =>
    //         r.cchkguidecode &&
    //         r.cchkguidecode == item.standardCode &&
    //         r.standardValue == item.standardValue &&
    //         item.id == r.id,
    //     );
    //     if (!o) {
    //       delrdDemandStandardlist.push({
    //         ...item,
    //         delFlag: 1,
    //       });
    //     }
    //   });
    // }

    // rdDemandStandard = rdDemandStandard.concat(delrdDemandStandardlist);
    rdDemandStandard = rdDemandStandard.filter((item) => item.standardName);

    const params = {
      ...form,
      sampleCode: form.sampleFlag != '0' ? form.sampleCode : '',
      samplesNum: form.sampleFlag != '0' ? form.samplesNum : '',
      sampleBatch: form.sampleFlag != '0' ? form.sampleBatch : '',
      askCompleteTime: form.askCompleteTime
        ? formatByDayjs(form.askCompleteTime, 'YYYY-MM-DD HH:mm:ss')
        : '',
      demandDate: form.demandDate ? formatByDayjs(form.demandDate, 'YYYY-MM-DD HH:mm:ss') : '',
      rdDemandStandard,
      requestNumUnit: form.requestFlag != 0 ? form.requestNumUnit : 0,
      requestNum: form.requestFlag != 0 ? form.requestNum : 0,
      samplePurpose: JSON.parse(JSON.stringify(form.samplePurpose)),
    };

    params.rdDemandFileEntity = params.rdDemandFileEntity.map((item) => {
      return {
        // ...item,
        fileName: item.fileName,
        fileUrl: item.fileUrl,
        demandCode: params.demandCode,
        tenantId: tenantTreeId.value,
      };
    });

    params.rdProjectUserEntity = params.rdProjectUserEntity.map((item) => {
      return {
        ...item,
        demandCode: params.demandCode,
        tenantId: tenantTreeId.value,
        rdCode: params.demandCode,
      };
    });
    if (params.samplePurpose && params.samplePurpose.length) {
      if (params.samplePurpose.includes('其他')) {
        const fIndex = params.samplePurpose.findIndex((item) => item == '其他');
        params.samplePurpose.splice(fIndex, 1, params.samplePurposeDesc);
        // params.samplePurpose[fIndex] = params.samplePurposeDesc;
      }
      params.samplePurpose = params.samplePurpose.join(',');
    } else {
      params.samplePurpose = '';
    }
    delete params.samplePurposeDesc;

    // if (form.demandTypeCode != '21' && form.demandTypeCode != '22' && form.demandTypeCode != '11') {
    //   params['requestFlag'] = 0;
    // }

    if (params.requestFlag == 0) {
      params.requestNum = 0;
      params.requestNumUnitCode = '';
      params.requestNumUnit = '';
      if (params.rdConnectEntity) {
        params.rdConnectEntity = params.rdConnectEntity.map((item) => {
          return {
            ...item,
            delFlag: 1,
          };
        });
      }
    }

    (form.id ? putObj(params) : addObj(params))
      .then((res) => {
        // uni.navigateBack();
        if (res.code == 0) {
          uni.showToast({
            mask: true,
            title: `单据${form.demandCode}保存成功`,
            icon: 'none',
          });
          if (isSubmit) {
            submitHandle();
          } else {
            init(form.id || res.data.id);
          }
        } else {
          uni.showToast({
            mask: true,
            title: `单据${form.demandCode}保存失败，失败原因${res.msg}`,
            icon: 'none',
          });
        }
      })
      .finally(() => {
        uni.hideLoading();
      });
  });
};

const getSampleUnit = (e) => {
  form.sampleUnitCode = e.selectedItems.label;
  form.sampleUnit = e.value;
};

const getRequestNumUnit = (e) => {
  form.requestNumUnitCode = e.selectedItems.label;
  form.requestNumUnit = e.value;
};

const changedemandType = (e) => {
  form.demandType = e.selectedItems.demandName;
};

const onSubmit = () => {
  showModal({
    title: '提示',
    content: '是否提交该单据',
    showCancel: true,
    confirm: () => {
      onSave(true);
    },
  });
};

const submitHandle = () => {
  // uni.showModal({
  //   title: '提示',
  //   content: '是否提交该单据',
  //   showCancel: true,
  //   success: ({ confirm, cancel }) => {
  //     if (confirm) {
  //       uni.showLoading({
  //         mask: true,
  //       });
  //       submitProcess(form.id)
  //         .then((res) => {
  //           if (res.code == 0) {
  //             uni.showToast({
  //               mask: true,
  //               title: `单据${form.demandCode}提交成功`,
  //               icon: 'none',
  //             });
  //             init(form.id);
  //           } else {
  //             uni.showToast({
  //               mask: true,
  //               title: `单据${form.demandCode}提交失败，失败原因：${res.msg}`,
  //               icon: 'none',
  //             });
  //           }
  //         })
  //         .finally(() => {
  //           uni.hideLoading();
  //         });
  //     }
  //   },
  // });

  uni.showLoading({
    mask: true,
  });
  submitProcess(form.id)
    .then((res) => {
      if (res.code == 0) {
        uni.showToast({
          mask: true,
          title: `单据${form.demandCode}提交成功`,
          icon: 'none',
        });
        init(form.id);
      } else {
        uni.showToast({
          mask: true,
          title: `单据${form.demandCode}提交失败，失败原因：${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const onDel = () => {
  showModal({
    title: '提示',
    content: '是否删除该单据',
    showCancel: true,
    confirm: () => {
      uni.showLoading({
        mask: true,
      });
      delObj([form.id])
        .then((res) => {
          if (res.code == 0) {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}删除成功`,
              icon: 'none',
            });
            // const pages = getCurrentPages();
            // const prevPage = pages[pages.length - 2]; // 上一个页面
            // prevPage.$vm.refresh();
            goBack();
            uni.$emit('refresh');
          } else {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}删除失败，失败原因：${res.msg}`,
              icon: 'none',
            });
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
  });
};
const opinionParasm = reactive({
  reviewOpinion: '',
  reviewType: 0,
  id: null,
});
const opinionList = ref([]);

const saveDemandOpinion = () => {
  const params = { ...opinionParasm, demandId: form.id, demandCode: form.demandCode };
  debugger;
  uni.showLoading({
    mask: true,
  });
  (opinionParasm.id ? updateOpinion(params) : saveOpinion(params))
    .then((res) => {
      if (res.code != 0) {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        });
        return;
      }
      init(form.id);
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const rdReviewOpinionHandle = () => {
  uni.showLoading({
    mask: true,
  });
  getOpinion({
    demandCode: form.demandCode,
  })
    .then((res) => {
      if (res.code != 0) {
        uni.showToast({
          mask: true,
          title: `获取数据失败，失败原因：${res.msg}`,
          icon: 'none',
        });
        return;
      }
      opinionList.value = res.data;
      const userInfos = userStore.userInfos;
      const cusPerson = userInfos.user.username;
      const o = res.data.find((item) => item.createBy == cusPerson);
      opinionParasm.reviewOpinion = o['reviewOpinion'];
      opinionParasm.id = o['id'];
    })
    .finally(() => {
      uni.hideLoading();
    });
};
// 撤回
const revokeComment = ref('');
const revokeShow = ref(false);
const handleClose = () => {
  revokeShow.value = false;
};
const onRevoke = () => {
  showModal({
    title: '提示',
    content: '是否撤回该单据',
    showCancel: true,
    confirm: () => {
      uni.showLoading({
        mask: true,
      });
      revokeProcess({
        id: form.id,
        instanceId: form.instanceId,
        comment: revokeComment.value,
      })
        .then((res) => {
          if (res.code == 0) {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}撤回成功`,
              icon: 'none',
            });
            handleClose();
            init(form.id);
          } else {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}撤回失败，失败原因：${res.msg}`,
              icon: 'none',
            });
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
  });
};
const onRevokeShow = () => {
  revokeShow.value = true;
};

// 审核信息
const comment = ref('');
const oncomplete = (type) => {
  if (type == '1' && !comment.value) {
    uni.showToast({
      title: '请填写审核意见',
      icon: 'none',
      mask: true,
    });
    return;
  }

  const params = {
    // ...form,
    taskId: form.taskId,
    comment: comment.value,
    id: form.id,
    approve: type == 0,
  };
  uni.showLoading({
    mask: true,
  });
  completeTask(params, form.id)
    .then((res) => {
      if (res.code == 0) {
        uni.showToast({
          title: '单据审核成功',
          icon: 'none',
          mask: true,
        });
        // uni.navigateBack({});
        form.instanceId = '';
        init(form.id);
        uni.$emit('refresh');
        // nextTick(() => {
        //   flowDetailsTableRef.value.getFlowDetails();
        // });
      } else {
        uni.showToast({
          mask: true,
          title: `单据审核失败，失败原因：${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const preview = (url) => {
  if (!url) return;
  uni.previewImage({
    urls: [url],
  });
};

const isCanCancelApprover = ref(false); // 是否能弃审
const getCancelApprover = () => {
  listLastNodePerson({
    processInstanceId: form.instanceId,
  })
    .then((res) => {
      const dataList = res.data;
      const { username } = userStore.userInfos.user;
      if (dataList.find((item) => item == username)) {
        isCanCancelApprover.value = true;
      } else {
        isCanCancelApprover.value = false;
      }
    })
    .finally(() => {});
};

const onCancelApprover = () => {
  showModal({
    title: '提示',
    content: '是否弃审该单据',
    showCancel: true,
    confirm: () => {
      uni.showLoading({
        mask: true,
      });
      reviveProcess(form.id)
        .then((res) => {
          if (res.code == 0) {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}弃审成功`,
              icon: 'none',
            });
            form.instanceId = '';
            init(form.id);
            // nextTick(() => {
            //   flowDetailsTableRef.value.getFlowDetails();
            // });
          } else {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}弃审失败，失败原因：${res.msg}`,
              icon: 'none',
            });
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
  });
};

const searchInvList = () => {
  if (
    form.taskId ||
    !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
  ) {
    return;
  }
  // selectpickerInvList.value = true;
  uni.$on('pm-inv', (e) => {
    console.log('sign', e);
    getInv(e);
  });
  uni.navigateTo({
    url: '/pages/pm/gongying/check-inv',
  });
};

const checkTargetList = ref([]);
const isShowCheckTarget = ref(false);
const getInv = (e) => {
  uni.$off('pm-inv');
  form.invName = e.cinvname;
  form.invStd = e.cinvstd;
  form.invCode = e.cinvcode;
  uni.showLoading({
    mask: true,
  });
  isShowCheckTarget.value = true;
  selectCheckTarget({
    cinvcode: e.cinvcode,
    tenantId,
  })
    .then((res) => {
      if (res.code === 0) {
        const l = checkTargetList.value
          .filter((item) => item.id)
          .map((item) => {
            return {
              ...item,
              delFlag: 1,
            };
          });

        delrdDemandStandardlist = delrdDemandStandardlist.concat(l);

        checkTargetList.value = res.data.map((item) => {
          return {
            ...item,
            addFlag: '0',
            // cusCheckTarget: '',
            cusCheckTarget: item.checktarget,
          };
        });
      } else {
        checkTargetList.value = [];
        uni.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
    })
    .catch((err) => {
      checkTargetList.value = [];
      uni.showToast({
        title: err.msg,
        icon: 'none',
      });
    })
    .finally(() => {
      uni.hideLoading();
    });
};

// 选择客户
const selectpickerInvList = ref(false);
const selectpickerInvListList = ref([]);
const hidepickerInvList = () => {
  selectpickerInvList.value = false;
};
const checkpickerInvList = (e) => {
  form.invName = e.invName;
  form.invStd = e.invStd;
  form.invCode = e.cinvcode;
};

const addCheckTargetList = () => {
  checkTargetList.value.push({
    cchkguidename: null,
    addFlag: '1',
    checktarget: null,
    cusCheckTarget: null,
  });
};

const delCheckTargetList = ref([]);
const delRow = (index, item) => {
  if (checkTargetList.value.length > 1) {
    showModal({
      title: '提示',
      content: '是否删除该需求指标',
      showCancel: true,
      confirm: () => {
        if (item.id) {
          const o = delCheckTargetList.value.find((i) => item.id == i.id);
          if (!o) {
            delCheckTargetList.value.push({
              ...item,
              delFlag: 1,
            });
          }
        }
        checkTargetList.value.splice(index, 1);
      },
    });
  }
};

const uploadComplete = (ref: any) => {
  const { id, fileName, url, fileType } = ref;
  console.log({
    id,
    fileName,
    url,
    fileType,
  });

  form.rdDemandFileEntity.push({
    fileName,
    fileUrl: url,
  });

  console.log('rdDemandFileEntity', form.rdDemandFileEntity);
};

const previewFileHandle = (file) => {
  uni.navigateTo({
    url: `/pages/pm/preview-online?url=${file}`,
  });
};

const removeFile = (index) => {
  showModal({
    title: '提示',
    content: '是否删除该附件',
    showCancel: true,
    confirm: () => {
      form.rdDemandFileEntity.splice(index, 1);
    },
  });
};

const columnChangedemandTypeCodeList = ({ selectedItem, resolve, finish }) => {
  setTimeout(() => {
    if (selectedItem.children && selectedItem.children.length) {
      resolve(selectedItem.children);
    } else {
      // 没有下一项时，执行完成
      finish();
    }
  }, 300);
};

const handleConfirmdemandTypeCodeList = (e) => {
  console.log(e);

  const { value } = e;
  const { selectedItems } = e;
  const o = selectedItems[selectedItems.length - 1];
  const demandTypeCode = o.value;
  form.demandTypeCode = demandTypeCode;
  // form.demandType = o['label'];
  form.demandType = e.selectedItems.map((item) => item.label).join(' / ');
  console.log(form.demandType, '1123123');

  getSampleList(demandTypeCode);

  //  判断是否提供样品
  if (demandTypeCode == '21') {
    requestFlagList.value = defaultrequestFlagList.filter((item) => item.value != 0);
    // requestFlagList.value = defaultrequestFlagList;
    form.requestFlag = 1;
    if (!form.requestNumUnit) {
      form.requestNumUnit = 'g';
      form.requestNumUnitCode = 'g';
    }
  } else {
    requestFlagList.value = defaultrequestFlagList;
    form.requestFlag = 0;
  }

  if (demandTypeCode == '43') {
    form.sampleFlag = '2';
    changesampleFlagName('2', '稀释', 1);
  }
};
const displayFormat = (selectedItems) => {
  if (selectedItems && selectedItems.length) {
    // return (
    //   selectedItems[selectedItems.length - 2].label +
    //   ' / ' +
    //   selectedItems[selectedItems.length - 1].label
    // );

    const l = selectedItems.map((item) => item.label);
    return l.join(' / ');
  }
  return null;
};

const samplaFlagList = ref([]);
const getSampleList = (demandTypeCode, isSetData = true) => {
  samplaFlagList.value = pm_sample_flag_gongying.value;
  // if (demandTypeCode == '10' || demandTypeCode == '11') {
  //   // 样品
  //   samplaFlagList.value = pm_sample_flag.value.filter((item) => item.value != 0);
  // } else if (demandTypeCode == '4' || demandTypeCode == '5' || demandTypeCode == '22') {
  //   // 样品
  //   samplaFlagList.value = pm_sample_flag.value;
  // } else {
  //   // samplaFlagList.value = pm_sample_flag.value.filter((item) => item.value == 0);
  //   samplaFlagList.value = pm_sample_flag.value;
  // }
  // if (isSetData) {
  //   const val = samplaFlagList.value[0].value;
  //   const { label } = samplaFlagList.value[0];
  //   form.sampleFlag = val;
  //   changesampleFlagName(val, label, 1);
  // }
};

const defaultrequestFlagList = [
  {
    label: '是',
    value: 1,
  },
  {
    label: '否',
    value: 0,
  },
];

const requestFlagList = ref([
  {
    value: 0,
    label: '否',
  },
  {
    value: 1,
    label: '是',
  },
]);

const checkPremiss = (k) => {
  return userStore.userInfos.authBtnList.some((v: string) => v === k);
};

// 处理数据转换为树形
// const transformTree = (data, len = 2, parent = '') => {
//   const newTree = [];
//   data.map((item) => {
//     if (
//       (parent &&
//         item.tradeCode.substr(0, parent.length) === parent &&
//         item.tradeCode.length === Number(len)) ||
//       (item.tradeCode.length == len && parent === '')
//     ) {
//       newTree.push({
//         tradeCode: item.tradeCode,
//         tradeName: `${item.tradeName}`,
//         tradeGrade: item.tradeGrade,
//         children: transformTree(data, len + 2, item.tradeCode),
//       });
//     }
//   });
//   return newTree;
// };

const transformTree = (data, len = 2, parent = '', ll = []) => {
  const newTree = [];
  data.map((item) => {
    if (
      (parent &&
        item.tradeCode.substr(0, parent.length) === parent &&
        item.tradeCode.length === Number(len)) ||
      (item.tradeCode.length == len && parent === '')
    ) {
      newTree.push({
        tradeCode: item.tradeCode,
        tradeName: `${item.tradeName}`,
        tradeGrade: item.tradeGrade,
        children: transformTree(data, len + 2, item.tradeCode),
      });
    }
  });
  return newTree;
};

const getEndTree = (data) => {
  let l = [];
  data.forEach((item) => {
    if (!(item.children && item.children.length)) {
      l.push(item);
    } else {
      l = l.concat(getEndTree(item.children));
    }
  });

  return l;
};

// const getapplicationTypeList = () => {
//   baseTrade({
//     current: 1,
//     size: 1000,
//   })
//     .then((res) => {
//       if (res.code != 0) {
//         uni.showToast({
//           mask: true,
//           title: `获取应用领域数据失败， 失败原因：${res.msg}`,
//           icon: 'none',
//         });
//         return;
//       }
//       // applicationTypeList.value = res.data.records.map((item) => {
//       //   return {
//       //     value: item.tradeName,
//       //     label: item.tradeCode,
//       //   };
//       // });

//       const i = transformTree(res.data);
//       const l = getEndTree(i);

//       // applicationTypeList.value = res.data.map((item) => {
//       //   return {
//       //     value: item.tradeName,
//       //     label: item.tradeCode,
//       //   };
//       // });

//       applicationTypeList.value = l.map((item) => {
//         return {
//           value: item.tradeName,
//           label: item.tradeCode,
//         };
//       });
//     })
//     .catch((err) => {
//       uni.showToast({
//         mask: true,
//         title: `获取应用领域数据失败， 失败原因：${err.msg || err}`,
//         icon: 'none',
//       });
//     });
// };

const setdemandTypeCascader = (type) => {
  let demandTypeL = [];
  demandTypeL = [
    {
      value: '51',
      label: '原料验证',
    },
    {
      value: '52',
      label: '设备验证',
    },
  ];

  demandTypeCascader.value = [demandTypeL];
};

const changeInv = (e) => {
  if (e.value == '') {
    const l = checkTargetList.value
      .filter((item) => item.id)
      .map((item) => {
        return {
          ...item,
          delFlag: 1,
        };
      });
    delrdDemandStandardlist = delrdDemandStandardlist.concat(l);

    checkTargetList.value = [];
    isShowCheckTarget.value = false;
    form.invStd = '';
    form.invCode = '';
  }
};
</script>

<style lang="scss" scoped>
@import '../experiment/components/table';

.card-detail {
  padding: 0 !important;
}

.wd-cell {
  padding-left: 0 !important;
}

.wd-card__title {
  border-left: 4px solid #2e5cf6 !important;
}

.pm-table {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  padding: 0 30rpx;

  .pm-title {
    box-sizing: border-box;
    padding-left: 20rpx;
    margin: 40rpx 0;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    border-left: 8rpx solid #2e5cf6;
    border-radius: 4rpx;
  }

  .pm-row {
    display: flex;
    min-height: 60rpx;
    border-bottom: 1px solid #f6f0f0;

    .pm-label {
      display: flex;
      align-items: center;
      width: 20%;
      font-size: 26rpx;
      color: #979494;
    }

    .pm-value {
      display: flex;
      flex: 1;
      align-items: center;
      font-size: 26rpx;
      color: #333;
    }
  }
}

.sign-main {
  // display: flex;
  // align-items: center;
  // justify-content: center;
  // width: 100%;
  // margin: 20rpx 0;
  position: fixed;
  right: 0rpx;
  bottom: 40rpx;
  width: 160rpx;
  height: 80rpx;
  line-height: 80rpx;
  color: white;
  text-align: center;
  background-color: rgb(77 128 240);

  // border-radius: 50%;
  border-top-left-radius: 40rpx;
  border-bottom-left-radius: 40rpx;
}

:deep(.label) {
  width: 160rpx !important;
}

.result-tag {
  padding: 6rpx 14rpx;
  font-size: 24rpx;
  color: white;
  background-color: #87d068;
  border-radius: 4rpx;
}

:deep(.wd-picker__cell) {
  padding: 0 !important;

  // padding: 0 20rpx !important;
  // font-size: 26rpx !important;
}

:deep(.wd-select-picker__cell) {
  padding: 0 !important;
}

// .wd-picker__value-wraper {
//   .wd-icon {
//     display: none !important;
//   }
// }

.seq-no-text {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.flow-btn-fixed {
  width: 100%;
  background-color: white;
  border-top: 1px solid #f2f2f1;
}

.btn_group {
  display: flex;
  justify-content: space-between;

  // margin: 0rpx 0 20rpx;
  // border-bottom: 1px solid #f2f2f1;

  .btn {
    display: flex;

    // width: 49%;
    flex: 1;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    // height: 40px;
    min-height: 40px;
    padding: 10rpx 0;
    font-size: 24rpx;
    color: black;

    // background-color: white !important;
    background-color: #dbecff !important;
    border-left: 1px solid #f7f7f7;
    border-radius: 0 !important;

    // color: white;
    border-radius: 6rpx;

    .btn-icon {
      width: 40rpx;
      height: 40rpx;
      margin-bottom: 8rpx;
    }
  }

  .danger {
    background-color: #f56c6c;
  }

  .primary {
    background-color: #409eff;
  }
}

.form-demandDesc {
  align-items: flex-start !important;
}
</style>
<style lang="scss">
/* .sample-unit-class {
    color: #9d9999 !important;
  
    .wd-icon {
      display: none !important;
    }
  
    .wd-picker__placeholder {
      margin-right: 0 !important;
      font-size: 20rpx !important;
      color: #9d9999 !important;
    }
  
    .wd-picker__value {
      margin-right: 0 !important;
      font-size: 20rpx !important;
      color: #9d9999 !important;
    }
  
    .wd-picker__arrow {
      display: none !important;
    }
  } */

.wd-picker,
.wd-select-picker {
  width: 100%;
}

.wd-textarea::after {
  height: 0;
}

:deep(.wd-picker__placeholder) {
  font-size: 28rpx !important;
  color: #bfbfbf !important;
}

:deep(.wd-input__placeholder) {
  font-size: 28rpx !important;
  color: #bfbfbf !important;
}

:deep(.wd-textarea__placeholder) {
  font-size: 28rpx !important;
  color: #bfbfbf !important;
}

.sample-unit-custom-value-class .wd-picker__placeholder {
  font-size: 20rpx !important;
  color: #bfbfbf !important;
}

.sample-unit-class {
  .wd-picker__placeholder {
    margin-right: 0 !important;
    font-size: 24rpx !important;
  }

  .wd-icon {
    display: none !important;
  }
}

:deep(.wd-picker__value) {
  color: #262626 !important;
}

:deep(.uni-input-input) {
  color: #262626 !important;
}

:deep(.wd-select-picker__value) {
  color: #262626 !important;
}

:deep(.uni-textarea-compute) {
  div {
    color: #262626 !important;
  }

  color: #262626 !important;
}

:deep(.uni-textarea-textarea) {
  color: #262626 !important;
}

:deep(.wd-textarea.is-auto-height::after) {
  display: none;
}

.reovke-textarea {
  box-sizing: border-box;
  flex: 1 !important;
  padding: 20rpx !important;

  :deep(.wd-textarea__value) {
    height: 100% !important;
  }
}

:deep(.wd-textarea.is-not-empty:not(.is-disabled)::after) {
  background-color: transparent !important;
}

.text {
  word-break: break-all;
  word-wrap: break-word;
}

.title_box .title_text {
  padding-left: 0 !important;
  margin-top: 10rpx !important;
}

.form-file {
  flex-direction: column;

  .label {
    width: 3rem !important;
  }

  .form-file-view {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    width: 100%;

    uni-button {
      margin: 5rpx 0 !important;
    }
  }
}

.info-row-item {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 6rpx 0;
  color: blue;
  word-break: break-all;
}

:deep(.wd-col-picker__cell) {
  padding: 0 !important;
}

.line-red td {
  background-color: rgb(255 186 186) !important;
}

.p {
  display: flex;
  flex: 1;
  flex-direction: column;
  height: 0;
}

:deep(.wd-navbar__left--hover) {
  background: none !important;
}

.exportModel {
  width: 100%;
  margin-top: 10rpx;
  font-size: 28rpx;
  color: #409eff;
  text-align: center;
}
:deep(.wd-navbar__right--hover) {
  background: none !important;
}
.printer-icon {
  display: flex;
  item-align: center;
  color: #fff;
}

:deep(.wd-textarea__inner) {
  min-height: 200rpx;
}
</style>
